import './index.css'
import Header from '../../components/Header'
import Footer from '../../components/Footer'
import Good from '../../components/Good'
import { getGoodsList } from '../../api/goods'
import { useState, useEffect, useRef } from 'react'

function Home() {
  const [goodsList, setGoodsList] = useState([
    {
      id: 1,
      name: '商品1',
      price: 100,
      image: 'https://picsum.photos/200/300',
    },
    {
      id: 2,
      name: '商品2',
      price: 200,
      image: 'https://picsum.photos/200/300',
    },
    {
      id: 3,
      name: '商品3',
      price: 300,
      image: 'https://picsum.photos/200/300',
    },
    {
      id: 4,
      name: '商品4',
      price: 400,
      image: 'https://picsum.photos/200/300',
    },
    {
      id: 5,
      name: '商品5',
      price: 500,
      image: 'https://picsum.photos/200/300',
    },
    {
      id: 6,
      name: '商品6',
      price: 600,
      image: 'https://picsum.photos/200/300',
    },
  ])
  const [isLoading, setIsLoading] = useState(false)
  const containerRef = useRef(null)

  // 请求更多商品数据
  const fetchMoreGoods = async () => {
    const res = await getGoodsList({
      page: Math.ceil(goodsList.length / 10) + 1
    })
    setGoodsList([...goodsList, ...res.data.data])
    setIsLoading(false)
  }

  const handleScroll = () => {
    const { scrollTop, scrollHeight, clientHeight } = containerRef.current
    // 将滚动相关属性转换为整数后再进行比较
    const scrollTopInt = Math.floor(scrollTop)
    const clientHeightInt = Math.floor(clientHeight)
    const scrollHeightInt = Math.floor(scrollHeight)
    if (scrollTopInt + clientHeightInt === scrollHeightInt - 1) {
      setIsLoading(true)
      fetchMoreGoods()
    }
  }

  return (
    <div className="home">
      <Header />
      <div
        className="goods-list"
        ref={containerRef}
        onScroll={handleScroll}
      >
        {goodsList.map((item, index) => (
          <Good key={item.id} {...item} />
        ))}
        {isLoading && <div>加载中...</div>}
      </div>
      <Footer />
    </div>
  )
}

export default Home
